<template>
  <FullPageModal
    v-model:visible="show"
    :title="t('components.mapModal.title')"
    :body-style="{ padding: 0 }"
    :z-index="1200"
    :custom-footer="true"
  >
    <div class="map-container">
      <div class="flex flex-row justify-between items-center">
        <a-input
          id="tipinput"
          v-model:value="locationStr"
          class="m-4 w-80"
          type="text"
          autocomplete="off"
          placeholder="搜地点"
          @keydown.enter="handleEnterSearch"
        >
          <template #prefix>
            <Icon type="icon-sousuo" class="text-xl" />
          </template>
        </a-input>
        <!-- <p class="m-0 pr-3"
          >{{ t("components.mapModal.lngLat") }}：{{
            resultData.longitude ? resultData.longitude + "，" + resultData.latitude : "--"
          }}</p
        > -->
      </div>
      <p class="pl-4">{{ t("components.mapModal.address") }}：{{ resultData.formattedAddress ?? "--" }}</p>
      <div v-if="visible" id="mapContainer"> </div>
      <div class="toolbar"> </div>
    </div>
    <template #footer>
      <div class="flex flex-row mt-4 justify-end">
        <a-button @click="handleCancel">{{ t("common.cancel") }}</a-button>
        <a-button type="primary" @click="handleOk">{{ t("common.ok") }}</a-button>
      </div>
    </template>
  </FullPageModal>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import AMapLoader from "@amap/amap-jsapi-loader";
import env from "/@/base/env";
import { getRegionsCodeAndSave } from "../api/aiot/zone";
import { RegionsItem } from "../api/aiot/zone/models";
import { message } from "ant-design-vue";

const props = defineProps<{
  visible: boolean;
}>();

window._AMapSecurityConfig = {
  securityJsCode: env.amapSKey,
};

const { t } = useI18n();
const show = ref<boolean>(false);
const geolocation = ref();
const locationStr = ref("");
const resultData = ref<RegionsItem>({});
let map: any = null; // 添加Markpoint
let temAMap: any = null; // Amap实例
let geoCoder: any = null;
let autoComplete: any = null;
function handleOk() {
  if (!resultData.value?.formattedAddress) {
    message.warning(t("components.mapModal.warnMsg"));
    return;
  }
  // confirmPosition();
  getRegionsCodeAndSave(resultData.value).then((res) => {});
  emits("update:visible", false);
  emits("ok", resultData.value);
}
function handleCancel() {
  emits("update:visible", false);
}
watch(
  () => props.visible,
  (v) => {
    show.value = v;
    if (!v) {
      // 清空tip下拉dom 防止初始化失败搜索功能无效
      document.querySelector(".amap-sug-result")?.remove();
    }
  }
);
function clearAllData() {
  resultData.value = {};
  locationStr.value = "";
}
const emits = defineEmits(["ok", "update:visible"]);
watch(show, (v) => {
  emits("update:visible", v);
  if (show.value) {
    // 初始化amap
    clearAllData(); // 清空旧数据
    AMapLoader.load({
      key: env.amapKey,
      version: "2.0",
      plugins: ["AMap.Geocoder", "AMap.AutoComplete", "AMap.Geolocation", "AMap.Event"],
    })
      .then((AMap) => {
        map = new AMap.Map("mapContainer", {
          resizeEnable: true,
        });
        map.on("click", handleClickMap);
        temAMap = AMap;
        init(AMap);
        geolocation.value = new AMap.Geolocation({
          enableHighAccuracy: true, //  是否使用高精度定位，默认:true
          timeout: 10000, //  超过10秒后停止定位，默认：无穷大
          maximumAge: 0, // 定位结果缓存0毫秒，默认：0
          convert: true, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: false, //  显示定位按钮，默认：true
          buttonPosition: "LB", // 定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(10, 20), //  定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true, //  定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //  定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //  定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          needAddress: true, // 是否返回地址信息
        });
        map.addControl(geolocation.value);
        geoCoder = new AMap.Geocoder();
      })
      .catch((e) => {
        console.warn("===========>AMapLoader load error", e);
      });
  }
});
var marker = null;
function handleClickMap(e) {
  marker && map.remove(marker);
  let position = [e.lnglat.getLng(), e.lnglat.getLat()];
  marker = new temAMap.Marker({
    position,
  });
  map.add(marker);
  queryAddressByLng(position);
}
function handleEnterSearch(e) {
  if (!geoCoder) return;
  geoCoder.getLocation(e.target._value, function (status, result) {
    if (status === "complete" && result.geocodes.length) {
      let lng = result.geocodes[0].location.lng;
      let lat = result.geocodes[0].location.lat;
      resultData.value = result.geocodes[0].addressComponent;
      resultData.value.adcode = result.geocodes[0].adcode;
      resultData.value.longitude = lng;
      resultData.value.latitude = lat;
      resultData.value.formattedAddress = result.geocodes[0].formattedAddress;
      // let a = Object.assign(resultData.value, result.geocodes[0].addressComponent);
      var lnglat = result.geocodes[0].location;
      marker && map.remove(marker);
      marker = new temAMap.Marker({
        position: lnglat,
      });
      map.add(marker);
      map.setFitView(marker);
    }
  });
}
function init(AMap) {
  let resultTip = document.getElementsByClassName("amap-sug-result");
  if (resultTip.length === 0) {
    autoComplete = null;
    autoComplete = new AMap.AutoComplete({
      input: "tipinput",
    });
  }
  geoCoder = new AMap.Geocoder();
  // 点击或选择搜索结果回调
  AMap.Event.addListener(autoComplete, ["select", "click"], function (e) {
    searchLocation(e);
  });
}
// 根据输入或选择的地址展示
function searchLocation(e) {
  if (!geoCoder) return;
  console.info("e", e);
  locationStr.value = e.poi.name;

  if (e.poi.location) {
    marker && map.remove(marker);
    marker = new temAMap.Marker({
      position: e.poi.location,
    });
    map.add(marker);
    map.setFitView(marker);
    resultData.value.longitude = e.poi.location.lng;
    resultData.value.latitude = e.poi.location.lat;
    resultData.value.formattedAddress = `${e.poi.name + "(" + e.poi.address + ")"}`;
    geoCoder.getAddress(e.poi.location, function (status, result) {
      if (result.info === "OK") {
        resultData.value = result.regeocode.addressComponent;
        resultData.value.longitude = e.poi.location.lng;
        resultData.value.latitude = e.poi.location.lat;
        resultData.value.adcode = result.regeocode.addressComponent.adcode;
        // 返回地址错误 例如搜索广州市白云山化学制药厂 返回地址错误
        // resultData.value.formattedAddress = result.regeocode.formattedAddress;
        resultData.value.formattedAddress = `${e.poi.name + "(" + (e.poi.address || "--") + ")"}`;
        marker && map.remove(marker);
        marker = new temAMap.Marker({
          position: e.poi.location,
        });
        map.add(marker);
        map.setFitView(marker);
      }
    });
  } else {
    geoCoder.getLocation(e.poi.name, function (status, result) {
      if (status === "complete" && result.geocodes.length) {
        let lng = result.geocodes[0].location.lng;
        let lat = result.geocodes[0].location.lat;
        resultData.value = result.geocodes[0].addressComponent;
        resultData.value.adcode = result.geocodes[0].adcode;
        resultData.value.longitude = lng;
        resultData.value.latitude = lat;
        resultData.value.formattedAddress = result.geocodes[0].formattedAddress;
        // let a = Object.assign(resultData.value, result.geocodes[0].addressComponent);
        var lnglat = result.geocodes[0].location;
        marker && map.remove(marker);
        marker = new temAMap.Marker({
          position: lnglat,
        });
        map.add(marker);
        map.setFitView(marker);
      }
    });
  }
}
function queryAddressByLng(lnglat: string[]) {
  if (!geoCoder) return;
  if (lnglat.length > 0) {
    geoCoder.getAddress(lnglat, function (status, result) {
      if (status === "complete" && result.regeocode) {
        resultData.value = result.regeocode.addressComponent;
        resultData.value.formattedAddress = result.regeocode.formattedAddress;
        resultData.value.longitude = lnglat[0];
        resultData.value.latitude = lnglat[1];
      } else {
      }
    });
  }
}
</script>
<style>
.amap-sug-result {
  z-index: 1400;
}
</style>
<style lang="less" scoped>
.amap-container {
  height: 100%;
}
.inputclass {
  z-index: 2000;
  width: 250px;
  appearance: none;
  box-sizing: border-box;
  padding: 0;
  font-variant: tabular-nums;
  list-style: none;
  font-feature-settings: tnum;
  display: inline-block;
  min-width: 0;
  padding: 5px 11px;
  color: #172b4d;
  font-size: 14px;
  line-height: 1.5715;
  background-color: #fff;
  background-image: none;
  border: 1px solid #e9ebee;
  border-radius: 4px;
  transition: all 0.3s;
}
.inputclass:focus {
  border-color: #6eaaff;
  box-shadow: 0 0 0 2px rgb(66 133 244 / 20%);
  border-right-width: 1px !important;
  outline: 0;
}
.inputclass:disabled {
  background-color: #eee;
}
#mapContainer {
  height: calc(100% - 20px);
}
.map-container {
  height: calc(100% - 90px);
}
</style>
